<template>
  <div class="weather-info-container">
    <!-- 实时天气概览 -->
    <el-row :gutter="20" class="weather-overview">
      <el-col :span="6">
        <el-card class="weather-card current-weather">
          <div class="weather-main">
            <div class="weather-icon">
              <el-icon size="48"><Sunny /></el-icon>
            </div>
            <div class="weather-info">
              <div class="temperature">{{ currentWeather.temperature }}°C</div>
              <div class="weather-desc">{{ currentWeather.description }}</div>
              <div class="location">{{ currentWeather.location }}</div>
            </div>
          </div>
          <div class="weather-details">
            <div class="detail-item">
              <span class="label">湿度：</span>
              <span class="value">{{ currentWeather.humidity }}%</span>
            </div>
            <div class="detail-item">
              <span class="label">风速：</span>
              <span class="value">{{ currentWeather.windSpeed }} m/s</span>
            </div>
            <div class="detail-item">
              <span class="label">气压：</span>
              <span class="value">{{ currentWeather.pressure }} hPa</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="weather-card forecast-card">
          <template #header>
            <div class="card-header">
              <span>未来7天天气预报</span>
              <el-button type="primary" size="small" @click="refreshWeather">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="forecast-list">
            <div
              v-for="(item, index) in weatherForecast"
              :key="index"
              class="forecast-item"
            >
              <div class="forecast-date">{{ item.date }}</div>
              <div class="forecast-icon">
                <el-icon><component :is="getWeatherIcon(item.weather)" /></el-icon>
              </div>
              <div class="forecast-weather">{{ item.weather }}</div>
              <div class="forecast-temp">
                <span class="high">{{ item.highTemp }}°</span>
                <span class="low">{{ item.lowTemp }}°</span>
              </div>
              <div class="forecast-wind">{{ item.windDirection }} {{ item.windLevel }}级</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="监测站点">
          <el-select
            v-model="queryForm.stationId"
            placeholder="请选择监测站点"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="station in weatherStations"
              :key="station.id"
              :label="station.name"
              :value="station.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select
            v-model="queryForm.dataType"
            placeholder="请选择数据类型"
            clearable
            style="width: 150px"
          >
            <el-option label="温度" value="temperature" />
            <el-option label="湿度" value="humidity" />
            <el-option label="降雨量" value="rainfall" />
            <el-option label="风速" value="windSpeed" />
            <el-option label="气压" value="pressure" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增数据
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="warning" @click="handleViewChart">
          <el-icon><TrendCharts /></el-icon>
          数据图表
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="stationName" label="监测站点" width="120" />
        <el-table-column prop="recordTime" label="记录时间" width="180" />
        <el-table-column prop="temperature" label="温度(°C)" width="100" />
        <el-table-column prop="humidity" label="湿度(%)" width="100" />
        <el-table-column prop="rainfall" label="降雨量(mm)" width="120" />
        <el-table-column prop="windSpeed" label="风速(m/s)" width="100" />
        <el-table-column prop="windDirection" label="风向" width="80" />
        <el-table-column prop="pressure" label="气压(hPa)" width="100" />
        <el-table-column prop="visibility" label="能见度(km)" width="100" />
        <el-table-column prop="weather" label="天气状况" width="100">
          <template #default="{ row }">
            <el-tag :type="getWeatherTagType(row.weather)">
              {{ row.weather }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dataSource" label="数据来源" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <WeatherInfoFormDialog
      v-model:visible="formDialogVisible"
      :form-data="currentFormData"
      :is-view="isView"
      @success="handleFormSuccess"
    />

    <!-- 图表弹窗 -->
    <WeatherChartDialog
      v-model:visible="chartDialogVisible"
      :chart-data="tableData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Delete, 
  Download, 
  TrendCharts,
  Sunny,
  Cloudy,
  Drizzling,
  Pouring
} from '@element-plus/icons-vue'
import WeatherInfoFormDialog from './components/WeatherInfoFormDialog.vue'
import WeatherChartDialog from './components/WeatherChartDialog.vue'

// 当前天气
const currentWeather = reactive({
  temperature: 25,
  description: '晴朗',
  location: '西音水库',
  humidity: 65,
  windSpeed: 3.2,
  pressure: 1013
})

// 天气预报
const weatherForecast = ref([
  { date: '今天', weather: '晴', highTemp: 28, lowTemp: 18, windDirection: '东南风', windLevel: 2 },
  { date: '明天', weather: '多云', highTemp: 26, lowTemp: 16, windDirection: '南风', windLevel: 1 },
  { date: '后天', weather: '小雨', highTemp: 22, lowTemp: 14, windDirection: '西南风', windLevel: 3 },
  { date: '周四', weather: '阴', highTemp: 24, lowTemp: 15, windDirection: '北风', windLevel: 2 },
  { date: '周五', weather: '晴', highTemp: 27, lowTemp: 17, windDirection: '东风', windLevel: 1 },
  { date: '周六', weather: '多云', highTemp: 25, lowTemp: 16, windDirection: '东南风', windLevel: 2 },
  { date: '周日', weather: '小雨', highTemp: 21, lowTemp: 13, windDirection: '西风', windLevel: 3 }
])

// 监测站点
const weatherStations = ref([
  { id: 1, name: '西音水库主站' },
  { id: 2, name: '大坝监测站' },
  { id: 3, name: '库区中心站' },
  { id: 4, name: '入库口站' },
  { id: 5, name: '出库口站' }
])

// 查询表单
const queryForm = reactive({
  stationId: '',
  dataType: '',
  dateRange: []
})

// 模拟数据与过滤分页辅助
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[randInt(0, arr.length - 1)]
const pad2 = (n: number) => (n < 10 ? '0' + n : '' + n)
const formatDateTime = (d: Date) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`

const generateMockData = () => {
  const count = randInt(10, 50)
  const stations = weatherStations.value.map(s => s.name)
  const windDirs = ['东风', '东南风', '南风', '西南风', '西风', '西北风', '北风', '东北风']
  const weathers = ['晴', '多云', '阴', '小雨', '中雨', '大雨']
  const sources = ['自动监测', '人工观测']
  const arr: any[] = []
  for (let i = 0; i < count; i++) {
    const weather = randomChoice(weathers)
    let rainfall = 0
    if (weather === '小雨') rainfall = +(Math.random() * 5 + 0.1).toFixed(1)
    else if (weather === '中雨') rainfall = +(Math.random() * 10 + 5).toFixed(1)
    else if (weather === '大雨') rainfall = +(Math.random() * 25 + 15).toFixed(1)
    const date = new Date(Date.now() - randInt(0, 30) * 24 * 3600 * 1000 - randInt(0, 23) * 3600 * 1000 - randInt(0, 59) * 60 * 1000)
    arr.push({
      id: Date.now() + i,
      stationName: randomChoice(stations),
      recordTime: formatDateTime(date),
      temperature: +(Math.random() * 20 + 10).toFixed(1),
      humidity: randInt(40, 90),
      rainfall,
      windSpeed: +(Math.random() * 8 + 0.5).toFixed(1),
      windDirection: randomChoice(windDirs),
      pressure: +(Math.random() * 40 + 990).toFixed(1),
      visibility: +(Math.random() * (weather === '晴' ? 10 : (weather === '多云' || weather === '阴') ? 6 : 4) + (weather === '晴' ? 10 : 4)).toFixed(1),
      weather,
      dataSource: randomChoice(sources)
    })
  }
  return arr
}

const applyFiltersAndPaginate = () => {
  if (allData.value.length === 0) {
    allData.value = generateMockData()
  }
  const { stationId, dateRange } = queryForm
  let filtered = allData.value.slice()
  if (stationId) {
    const station = weatherStations.value.find(s => s.id === stationId)
    if (station) filtered = filtered.filter(item => item.stationName === station.name)
  }
  if (Array.isArray(dateRange) && dateRange.length === 2 && dateRange[0] && dateRange[1]) {
    const start = Date.parse(String(dateRange[0]).replace(/-/g, '/'))
    const end = Date.parse(String(dateRange[1]).replace(/-/g, '/'))
    filtered = filtered.filter(item => {
      const t = Date.parse(String(item.recordTime).replace(/-/g, '/'))
      return t >= start && t <= end
    })
  }
  pagination.total = filtered.length
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  const endIndex = startIndex + pagination.pageSize
  tableData.value = filtered.slice(startIndex, endIndex)
}

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗控制
const formDialogVisible = ref(false)
const chartDialogVisible = ref(false)
const currentFormData = ref(null)
const isView = ref(false)

// 获取天气图标
const getWeatherIcon = (weather: string) => {
  const iconMap = {
    '晴': 'Sunny',
    '多云': 'Cloudy',
    '阴': 'Cloudy',
    '小雨': 'Drizzling',
    '中雨': 'Pouring',
    '大雨': 'Pouring'
  }
  return iconMap[weather] || 'Sunny'
}

// 获取天气标签样式
const getWeatherTagType = (weather: string) => {
  const typeMap = {
    '晴': 'success',
    '多云': 'primary',
    '阴': 'info',
    '小雨': 'warning',
    '中雨': 'warning',
    '大雨': 'danger',
    '暴雨': 'danger'
  }
  return typeMap[weather] || ''
}

// 模拟API - 获取气象数据列表
const fetchWeatherList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取气象数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除气象数据
const deleteWeatherData = async (ids: number[]) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    applyFiltersAndPaginate()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 导出数据
const exportWeatherData = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 刷新天气
const refreshWeather = () => {
  ElMessage.success('天气数据已刷新')
  // 这里可以调用实际的天气API
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  fetchWeatherList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    stationId: '',
    dataType: '',
    dateRange: []
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentFormData.value = null
  isView.value = false
  formDialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentFormData.value = { ...row }
  isView.value = true
  formDialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentFormData.value = { ...row }
  isView.value = false
  formDialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除站点"${row.stationName}"的气象数据吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteWeatherData([row.id])
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 条气象数据吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteWeatherData(selectedIds.value)
  })
}

// 导出
const handleExport = () => {
  exportWeatherData()
}

// 查看图表
const handleViewChart = () => {
  chartDialogVisible.value = true
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  applyFiltersAndPaginate()
}

// 表单成功回调
const handleFormSuccess = () => {
  fetchWeatherList()
}

// 初始化
onMounted(() => {
  fetchWeatherList()
})
</script>

<style scoped>
.weather-info-container {
  padding: 20px;
}

.weather-overview {
  margin-bottom: 20px;
}

.weather-card {
  height: 100%;
}

.current-weather {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.current-weather :deep(.el-card__body) {
  padding: 20px;
}

.weather-main {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.weather-icon {
  margin-right: 20px;
}

.temperature {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 5px;
}

.weather-desc {
  font-size: 16px;
  margin-bottom: 5px;
}

.location {
  font-size: 14px;
  opacity: 0.8;
}

.weather-details {
  display: flex;
  justify-content: space-between;
}

.detail-item {
  text-align: center;
}

.detail-item .label {
  display: block;
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.detail-item .value {
  font-size: 16px;
  font-weight: bold;
}

.forecast-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forecast-list {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.forecast-item {
  flex: 1;
  text-align: center;
  padding: 15px 10px;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s;
}

.forecast-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.forecast-date {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.forecast-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.forecast-weather {
  font-size: 14px;
  margin-bottom: 8px;
}

.forecast-temp {
  margin-bottom: 5px;
}

.forecast-temp .high {
  font-weight: bold;
  margin-right: 5px;
}

.forecast-temp .low {
  color: #999;
}

.forecast-wind {
  font-size: 12px;
  color: #666;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>